package com.liukai.bishe.ui.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

import com.liukai.bishe.R;
import com.liukai.bishe.model.doman.transaction.Transaction;
import com.liukai.bishe.model.doman.transaction.TransactionTotal;
import com.liukai.bishe.model.doman.transaction.TransactionUseTime;
import com.liukai.bishe.model.doman.transaction.TransactionUserTimeMessageList;
import com.liukai.bishe.presenter.transactionPresenter.ITransactionPresenter;
import com.liukai.bishe.presenter.transactionPresenter.impl.ITransactionPresenterImpl;
import com.liukai.bishe.ui.broadcastReceiver.TransactionBroadcastReceiver;
import com.liukai.bishe.ui.dialog.StopTransactionDialog;
import com.liukai.bishe.ui.service.BiSheService;
import com.liukai.bishe.ui.service.CountDownService;
import com.liukai.bishe.utils.Constants;
import com.liukai.bishe.utils.DateUtils;
import com.liukai.bishe.utils.ToastUtil;
import com.liukai.bishe.view.ITransactionCallBack;
import com.robinhood.ticker.TickerUtils;
import com.robinhood.ticker.TickerView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class CountDownActivity extends AppCompatActivity implements TransactionBroadcastReceiver.ITransactionUpdateUI,ITransactionCallBack {

    private Unbinder mBind;

    private Context mContext = CountDownActivity.this;

    private Transaction mTransaction;

    // 时间显示
    @BindView(R.id.tickerView)
    public TickerView mTickerView;

    // 事务标题
    @BindView(R.id.title)
    public TextView tvTitle;

    @BindView(R.id.btnBack)
    public ImageView btnBack;

    private CountDownService mCountDownService;
    private boolean mBound = false;

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            CountDownService.MyBinder binder = (CountDownService.MyBinder)iBinder;
            mCountDownService = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBound = false;
        }
    };
    private Intent mIntent;
    private String mTimeString;
    private int mTime;
    private ITransactionPresenter mITransactionPresenter;
    private StopTransactionDialog mStopTransactionDialog;
    private TransactionUseTime mTransactionUseTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_count_down);

        mBind = ButterKnife.bind(this);
        mTickerView.setCharacterLists(TickerUtils.provideNumberList());

        mITransactionPresenter = new ITransactionPresenterImpl();
        mITransactionPresenter.registerCallback(this);

        iniData();
        ininLisenter();



    }

    public void unBindService() {
        if (mBound) {
            unbindService(mServiceConnection);
            mBound = false;
        }
    }

    public void getData(View view) {
        if (mBound) {
            Toast.makeText(this, "获取到的随机数：" + mCountDownService.getRandomNumber(), Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "服务未绑定", Toast.LENGTH_SHORT).show();
        }
    }

    private void iniData() {

        // 获取开始的事务信息
        mTransaction = (Transaction)getIntent().getSerializableExtra("transaction");
        mTransactionUseTime = new TransactionUseTime();
        long timeStamp = System.currentTimeMillis();
//        long time = System.currentTimeMillis();
        ToastUtil.log(mContext,"开始时间戳",timeStamp+"");

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(timeStamp);
        String dateTime = simpleDateFormat.format(date);
        ToastUtil.log(mContext,"当前开始时间",dateTime+"");
        mTransactionUseTime.setStarttime(String.valueOf(timeStamp));
        mTransactionUseTime.setId(mTransaction.getId());
        mTransactionUseTime.setTransactionname(mTransaction.getTransactionname());
        mTransactionUseTime.setUsername(mTransaction.getUsername());

        // 注册广播，实时接收服务传递回来的数据
        TransactionBroadcastReceiver transactionBroadcastReceiver = new TransactionBroadcastReceiver();
        transactionBroadcastReceiver.registerITransactionUpdateUI(this);
        IntentFilter filter=new IntentFilter();
        filter.addAction("com.liukai.bishe.ui.service.CountDownService");
        registerReceiver(transactionBroadcastReceiver,filter);

        // 获取事务需要执行的时间
        mTime = Integer.parseInt(mTransaction.getTime());
        mTimeString = getSimpleTime(mTime *60+"");
        mTickerView.setText(mTimeString);

        // 获取事务标题
        String title = mTransaction.getTransactionname();
        tvTitle.setText(title);

        // 绑定并开启服务
        bindService();

    }

    public void bindService() {
        mIntent = new Intent(this, CountDownService.class);
        mIntent.putExtra("time",mTime*60+"");
        startService(mIntent);
        bindService(mIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    private void ininLisenter() {

        // 返回按钮
        btnBack.setOnClickListener(view -> {

            mStopTransactionDialog = new StopTransactionDialog(mContext,mITransactionPresenter,
                    mTransactionUseTime,this);
            mStopTransactionDialog.show();

        });

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBound) {
            stopService(mIntent);
            unbindService(mServiceConnection);
            mBound = false;
        }

        mITransactionPresenter.registerCallback(this);

    }

    /**
     * 获取服务传递给广播的数据
     * @param string
     */
    @Override
    public void updateUI(String string) {
        String timeString = getSimpleTime(string);
        mTickerView.setText(timeString);
        if (mStopTransactionDialog != null){
            mStopTransactionDialog.setTime(string);
        }
        if (Long.valueOf(string) <= 0){
            long timeStamp = System.currentTimeMillis();
            ToastUtil.log(mContext,"当前结束时间戳",timeStamp+"");

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date(timeStamp);
            String dateTime = simpleDateFormat.format(date);
            ToastUtil.log(mContext,"当前结束时间",dateTime+"");
            mTransactionUseTime.setStoptime(String.valueOf(timeStamp));
            long totalTime = timeStamp - Long.parseLong(mTransactionUseTime.getStarttime());

            String timeString1 = DateUtils.longTimeToMinuties(totalTime);
            if (Long.valueOf(timeString1) < 1){
                ToastUtil.show(mContext,"执行1分钟以下的任务，不予计时");
            }else {
                mTransactionUseTime.setThistotaltime(String.valueOf(totalTime));
                // 开启Presenter
                if(Integer.parseInt(string) == 0){
                    mITransactionPresenter.startTransaction(mTransactionUseTime);
                    Intent intent = new Intent(mContext,BiSheService.class);
                    intent.putExtra("title",mTransaction.getTransactionname());
                    ContextCompat.startForegroundService(mContext,intent);
                }
            }
            finish();
        }

//        ToastUtil.log(mContext,"CountDownActivity=================>" + string);
    }

    /**
     * 将秒转换为分秒
     * @param string
     * @return
     */
    private String getSimpleTime(String string){
        int time = Integer.parseInt(string);
        int minutes = time / 60;
        int remainingSeconds = time % 60;
        StringBuilder sb = new StringBuilder();
        if (minutes < 10){
            sb.append("0" + minutes);
        }else{
            sb.append(minutes);
        }
        sb.append(":");
        if (remainingSeconds < 10){
            sb.append("0" + remainingSeconds);
        }else{
            sb.append(remainingSeconds);
        }
        return sb.toString();
    }

    @Override
    public boolean onKeyDown(int keyCode,KeyEvent event){
        if(keyCode==KeyEvent.KEYCODE_BACK){
            mStopTransactionDialog = new StopTransactionDialog(mContext,mITransactionPresenter,
                    mTransactionUseTime,this);
            mStopTransactionDialog.show();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }//屏蔽返回键

    /**
     * 执行一次事务成功保存至服务器，并返回
     * @param object
     */
    @Override
    public void resultTrsaction(Object object) {
        List<TransactionUseTime> transactionUseTimeList = (List<TransactionUseTime>)object;
//        String code = transactionUserTimeMessageList.getCode();
//        List<TransactionUseTime> transactionUseTimeList = transactionUserTimeMessageList.getTransactionUseTimes();
//
//        if(code.equals("6001")){
            ToastUtil.log(mContext,"执行事务保存至服务器成功返回",transactionUseTimeList.toString());
            Constants.setTransactionUseTimeList(transactionUseTimeList);
//        }

        mITransactionPresenter.findTransactionTotal(Constants.getUserInfo().getUsername());

    }

    /**
     * 获取服务器返回的该用户每一项任务总的执行情况
     * @param transactionTotalList
     */
    @Override
    public void resultTransactionTotal(List<TransactionTotal> transactionTotalList) {
        Constants.setTransactionTotalList(transactionTotalList);
    }

    @Override
    public void result(Object object) {

    }


}
